package com.my;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.my.api.MyRpcRequest;
import com.my.api.MyRpcResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Arrays;

//@EnableAutoConfiguration
@SpringBootApplication
@RestController
public class MyProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyProviderApplication.class, args);
    }

    @ResponseBody
    @RequestMapping("/sayHi")
    public String sayHi() {
        return "hiiiii!!!!";
    }

    @Resource
    private MyRpcProviderResolver resolver;

    @ResponseBody
    @RequestMapping("/invoke")
    public String invoke(@RequestBody MyRpcRequest rpcRequest) {
        MyRpcResponse rpcResponse = new MyRpcResponse();
        try {
            // 获取服务类名
            String serviceName = rpcRequest.getServiceClass();
            // 查找实现类
            Object resolveObj = resolver.resolve(serviceName);
            // 要调用的方法
            Method method = resolveObj.getClass().getMethod(rpcRequest.getMethod(), paramClsArr(rpcRequest.getParams()));
//            Method method = resolveObj.getClass().getMethod(rpcRequest.getMethod(), Integer.class);
            // 执行方法获取结果
            Object invokeResult = method.invoke(resolveObj, rpcRequest.getParams());
            rpcResponse.setException(null);
            rpcResponse.setResult(JSON.toJSONString(invokeResult, SerializerFeature.WriteClassName));
            rpcResponse.setStatus("OK");
        } catch (Exception e) {
            e.printStackTrace();
            // TODO 这里处理异常时的情况，同样返回MyRpcResponse，但要设置异常信息
//            MyRpcResponse rpcResponse = new MyRpcResponse();
            rpcResponse.setException(e);
            rpcResponse.setResult("");
            rpcResponse.setStatus("FAIL");
        }
        return JSON.toJSONString(rpcResponse);
    }

    private Class[] paramClsArr(Object[] params) {
        return Arrays.stream(params).map(v -> v.getClass()).toArray(size -> new Class[size]);
    }
}

